package hu.crs.demobank.function.login;

import hu.crs.demobank.authentication.AuthenticationManager;
import hu.crs.demobank.session.SessionManager;
import hu.crs.demobank.user.User;
import hu.crs.demobank.user.UserManager;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

public class Login {
	
	public Login() {
		super();
		// TODO Auto-generated constructor stub
	}

	private static Logger logger = Logger.getLogger(Login.class);
	private String userName;
	private String password;
	private UIComponent submitButton;
	
	public String checkLogin() throws Exception {
		logger.debug("userName" +userName);
		logger.debug("userName" +userName);
		
		if (AuthenticationManager.checkLogin(userName, password)) {
			HttpSession session = SessionManager.getNewSession();
			session.setAttribute("loggedIn", "true");
			User user = UserManager.initUser(userName);
			session.setAttribute("user", user);
			
			return "success";
		}
		
		FacesMessage message= new FacesMessage("Incorrect username or password!");
		FacesContext context = FacesContext.getCurrentInstance();
		context.addMessage(submitButton.getClientId(context), message);
		
		return "failure";
		
	}
	
	

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public UIComponent getSubmitButton() {
		return submitButton;
	}

	public void setSubmitButton(UIComponent submitButton) {
		this.submitButton = submitButton;
	}

}
